<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>查找城市</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <div class="container">
      <div class="input-box">
        <input type="text" placeholder="输入城市名称，按下回车搜索" />
      </div>
      <div class="result-box">
        <ul class="result-list">
          <!-- <li class="result-item">
            <p class="item-code">区域编码</p>
            <p class="item-name">城市名称</p>
          </li> -->
          <!-- <li class="result-item">
            <p class="item-code">120000</p>
            <p class="item-name">天津市</p>
          </li> -->
        </ul>
      </div>
    </div>
    <script type="module">
      //城市的json数据
      import { city } from "./city.js";
      let html_str = `<li class="result-item">
            <p class="item-code">区域编码</p>
            <p class="item-name">城市名称</p>
          </li>`;
      //获取input和ul
      const input_dom = document.querySelector(".input-box input");
      const ul_dom = document.querySelector(".result-list");
      ul_dom.innerHTML = html_str;
      //监听input的输入事件
      /* input_dom.addEventListener("compositionend", (event) => {
        //获取输入的值
        const name = event.data;
        //查找对应结果
        const list = getCityList(name);
        //结果转换成dom结构,插入到ul中
        addliDom(list);
      }); */
      input_dom.addEventListener("change", (event) => {
        const name = input_dom.value;
        const list = getCityList(name);
        addliDom(list);
      });
      function getCityList(cname) {
        const list = [];
        //清空str的数据
        ul_dom.innerHTML = html_str;
        city.forEach((item) => {
          if (item.provinceName.includes(cname)) {
            list.push({ name: item.provinceName, code: item.provinceCode });
          }
          if (item.provinceType !== 1) {
            item.cities.forEach((i) => {
              if (i.cityName.includes(cname)) {
                list.push({ name: i.cityName, code: i.cityCode });
              }
            });
          }
        });
        return list;
      }
      function addliDom(mlist) {
        let str = "";
        mlist.forEach((item) => {
          str += `<li class="result-item"><p class="item-code">${item.code}</p><p class="item-name">${item.name}</p></li>`;
        });
        ul_dom.innerHTML = html_str + str;
      }
    </script>
  </body>
</html>
